package tmproject.hlhj.fhp.tmvote.activitys

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import kotlinx.android.synthetic.main.aty_signup.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import tmproject.hlhj.fhp.tmvote.BaseAty
import tmproject.hlhj.fhp.tmvote.Content
import tmproject.hlhj.fhp.tmvote.R
import tmproject.hlhj.fhp.tmvote.beans.BaseBean
import tmproject.hlhj.fhp.tmvote.beans.SignUpRuleBean
import tmproject.hlhj.fhp.tmvote.beans.TempEvent
import tmproject.hlhj.fhp.tmvote.customView.AgainDialog
import tmproject.hlhj.fhp.tmvote.customView.ChoosePop
import tmproject.hlhj.fhp.tmvote.module.SignUpModule
import tmproject.hlhj.fhp.tmvote.presenters.SignUpPresenter
import tmproject.hlhj.fhp.tmvote.utils.FileUtil
import tmproject.hlhj.fhp.tmvote.utils.NewGlideEngin
import tmproject.hlhj.fhp.tmvote.utils.PhoneUtils
import tmproject.hlhj.fhp.tmvote.utils.ToastUtil
import tmproject.hlhj.fhp.tmvote.views.SignUpView
import java.io.File

/**
 * Created by Never Fear   on 2018\8\7 0007.
Never More....
 */
class SignUpAty :BaseAty<SignUpView,SignUpPresenter>(), SignUpView {
    private var filePath:String?=null
    private var signRule=ArrayList<String>()
    private var pop:ChoosePop?=null

    private lateinit var adp:BaseQuickAdapter<String,BaseViewHolder>

    override fun createPresenter(): SignUpPresenter {
        return SignUpPresenter()
    }

    override fun getContentId(): Int {
        return R.layout.aty_signup
    }

    /*VIew*/
    override fun initView() {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        tvTittle.text=intent.getStringExtra("title")
        EventBus.getDefault().register(this)
        topBack.setBackgroundResource(Content.vote_detail_head)//头部图片更换
        img1.setImageResource(Content.vote_detail_head_women)//跳舞的女人背景更换
        lo4.setBackgroundResource(Content.vote_rule_bac)//背景框
        btCommit.setBackgroundResource(Content.vote_commit_bottom_bac)
        tv2.setTextColor(Color.parseColor(Content.vote_text_color))

        signRule.addAll(intent.getStringArrayListExtra("rule"))
        adp=object :BaseQuickAdapter<String,BaseViewHolder>(R.layout.rule_item,signRule){
            override fun convert(helper: BaseViewHolder?, item: String?) {
                helper?.setText(R.id.itemTv,item)
            }
        }
        ruleList.adapter=adp
        ruleList.layoutManager=LinearLayoutManager(this@SignUpAty,LinearLayoutManager.VERTICAL,false)
        tvTime.text="活动时间 ：${intent.getStringExtra("voteS")}至${intent.getStringExtra("voteE")}"
        signUpTime.text="报名时间：${intent.getStringExtra("signS")}至${intent.getStringExtra("signE")}"
        voteTime.text="投票时间：${intent.getStringExtra("voteS")}至${intent.getStringExtra("voteE")}"
        tvInfo.text="个人\n简介"
        tvIMG.text="上传\n图片"
    }
    @SuppressLint("MissingSuperCall")
    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    override fun upLoadImg() {
    }

    override fun logicStart() {
    }

    override fun bindView(): SignUpView {
        return this
    }

    private val PICK_IMG: Int=111
    private val PICK_IMG_FROM_CAMERA: Int=112

    override fun setListener() {
        /*照片*/
        btImg.setOnClickListener {
            val lp = window.attributes
            lp.alpha=0.5f
            window.attributes=lp
            if (null==pop){
                pop= ChoosePop(this@SignUpAty,object :ChoosePop.OnPopChooseListener{
                    override fun photo() {
                        Matisse.from(this@SignUpAty)
                                .choose(MimeType.ofImage())
                                .maxSelectable(1)
                                .showSingleMediaType(true)
                                .countable(true)
                                .thumbnailScale(0.85f)
                                .theme(R.style.Matisse_Zhihu)
                                .imageEngine(NewGlideEngin())
                                .forResult(PICK_IMG)
                    }

                    override fun camera() {
                        val intent = Intent(this@SignUpAty, CameraAty::class.java)
                        startActivity(intent)
                    }
                })
            }
            pop?.showAtLocation(father,Gravity.BOTTOM,0,0)
        }

        btDelet.setOnClickListener {
            img.visibility= View.VISIBLE
            tv1.visibility=View.VISIBLE
            photo.visibility=View.GONE
            btDelet.visibility=View.GONE

            filePath=null
        }
        btDelet.performClick()
        btDelet.visibility=View.GONE

        btCommit.setOnClickListener {
            if (etName.text.isEmpty()){
                ToastUtil.toast("姓名不能为空")
                return@setOnClickListener
            }

            if (etPhone.text.isEmpty()){
                ToastUtil.toast("手机号不能为空")
                return@setOnClickListener
            }

            if (!PhoneUtils.isMobileNO(etPhone.text.toString())){
                ToastUtil.toast("手机号格式不正确")
                return@setOnClickListener
            }

            if (etInfo.text.isEmpty()){
                ToastUtil.toast("简介不能为空")
                return@setOnClickListener
            }

            if (filePath==null){
                ToastUtil.toast("图片未选择！")
                return@setOnClickListener
            }
            if (intent.getStringExtra("price").equals("0.00")){
                presenter?.signUp(Content.UID,etName.text.toString(),etPhone.text.toString(),etInfo.text.toString(),
                        intent.getIntExtra("id",0).toString(),null,File(filePath),this@SignUpAty
                )
            }else{
                val i = Intent(this@SignUpAty, PayAty::class.java)
                i.putExtra("uid",Content.UID)
                i.putExtra("name",etName.text.toString())
                i.putExtra("phone",etPhone.text.toString())
                i.putExtra("des",etInfo.text.toString())
                i.putExtra("id",intent.getIntExtra("id",0).toString())
                i.putExtra("imgPath",filePath)
                i.putExtra("price",intent.getStringExtra("price"))
                startActivity(i)
                finish()
            }


        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!= Activity.RESULT_OK)return
        when(requestCode){
            PICK_IMG->{
                val pathResult = Matisse.obtainPathResult(data)
                val path = pathResult[0]
                filePath=path
                Glide.with(this@SignUpAty).load(path).into(photo)
                photo.visibility=View.VISIBLE
                img.visibility= View.GONE
                tv1.visibility=View.GONE

                btDelet.visibility=View.VISIBLE
            }
            PICK_IMG_FROM_CAMERA->{
                val bitmap = data?.getParcelableExtra<Bitmap>("bit")
                val imageFile = FileUtil.createImageFile(bitmap!!, this@SignUpAty)
                filePath=imageFile.path

                Glide.with(this@SignUpAty).load(filePath).into(photo)
                photo.visibility=View.VISIBLE
                img.visibility= View.GONE
                tv1.visibility=View.GONE
            }
        }
    }
    override fun signUp(baseBean: BaseBean) {
        loadingDialog.dismiss()
        if (baseBean.code==200){
            AgainDialog(this,object :AgainDialog.AgainListener{
                override fun yes() {
                    finish()
                }
            }).show()
            ToastUtil.toast("报名成功")
        }else if (baseBean.code==500){
            if (baseBean.message.equals("选手已存在")){

            }

        }
    }

    override fun setVoteRule(ruleBean: SignUpRuleBean) {

    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    fun getBitMap(tempEvent: TempEvent){
        val bitmap = tempEvent.bitmap
        val imageFile = FileUtil.createImageFile(bitmap!!, this@SignUpAty)
        filePath=imageFile.path
        Glide.with(this@SignUpAty).load(filePath).into(photo)
        photo.visibility=View.VISIBLE
        img.visibility= View.GONE
        tv1.visibility=View.GONE
        btDelet.visibility=View.VISIBLE

    }
}
